/**
 * 
 */
package com.pocketsweet.ui;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.sns.SNSType;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.pocketsweet.C;
import com.pocketsweet.R;
import com.pocketsweet.service.LoginService;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.ui.uilib.MyOnTouchListener;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;

/**
 * @author hantian
 * 
 */
@ContentView(R.layout.activity_login)
public class Login extends Activity {

	@ViewInject(R.id.etMobile)
	private EditText mobile;

	@ViewInject(R.id.etPassword)
	private EditText password;

	@ViewInject(R.id.forgetPwd)
	private TextView forgetPwd;

	@ViewInject(R.id.tvWeChat)
	private TextView tvWeChat;

	@ViewInject(R.id.tvQQ)
	private TextView tvQQ;

	@ViewInject(R.id.tvWeibo)
	private TextView tvWeibo;

	@ViewInject(R.id.mainHeader)
	private HeaderLayout header;

	private LoadingDailog mLoadingDialog;
	private String passwordStr;
	private boolean isLogin = false;
	private long mExitTime = 0;// 退出事件用到的事件
	private LoginService myLoginSevice;// 友盟第三方登陆service
	private SNSType type = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		myLoginSevice = new LoginService(Login.this);
		mLoadingDialog = ToolKits.createLoadingDialog(Login.this, "登陆中...");
		mLoadingDialog.setText("加载中");
		forgetPwd.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); // 设置下划线
		setHeaderFunction();
		String status = getIntent().getStringExtra("status");
		if (!StringUtils.isEmpty(status)
				&& status.equals(String.valueOf(C.USER_STATUS_DISABLE))) {
			final MyAlertDialog dialog = new MyAlertDialog(Login.this)
					.builder().setMsg("由于用户举报过多，你已被封号").setTitle("提示")
					.setPositiveButton("确定", new OnClickListener() {
						@SuppressLint("SimpleDateFormat")
						@Override
						public void onClick(View v) {
						}
					});
			dialog.show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		/** 使用SSO授权必须添加如下代码 */
		UMSsoHandler ssoHandler = myLoginSevice.mController.getConfig()
				.getSsoHandler(requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onDestroy();
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setRightText("注册");
		header.setLeftText("");
		header.setMiddleText("登录");
		header.setRighttContainerClickListener(new onRightContainerListener() {

			@Override
			public void onClick() {
				// TODO 注册
				Intent intent = new Intent(Login.this, Register.class);
				Login.this.startActivity(intent);
				Login.this.finish();
			}
		});
		header.setLeftContainerClickListener(new onLeftContainerListener() {
			
			@Override
			public void onClick() {
				Intent intent = new Intent(Login.this, TempMain.class);
				Login.this.startActivity(intent);
				Login.this.finish();
			}
		});
	}

	@OnClick(R.id.btn_login)
	public void onLoginClick(View view) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mobile.getWindowToken(), 0);
		InputMethodManager imm2 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm2.hideSoftInputFromWindow(password.getWindowToken(), 0); // 隐藏软键盘

		String phone = mobile.getText().toString();
		passwordStr = password.getText().toString();
		myLoginSevice.login(phone, passwordStr); // 普通登录
	}

	@OnClick(R.id.forgetPwd)
	public void onForgetClick(View view) {
		Intent intent = new Intent(Login.this, ForgetPassword.class);
		Login.this.startActivity(intent);
		Login.this.finish();
	}

	@OnClick(R.id.tvWeibo)
	public void onLoginByWeiboClick(View view) { // 微博登录
		myLoginSevice.loginWithSina();
	}

	private IWXAPI mWeixinAPI;
	@OnClick(R.id.tvWeChat)
	public void onLoginByWeChatClick(View view) { // TODO //微信登录
		if (mWeixinAPI == null) {
			mWeixinAPI = WXAPIFactory.createWXAPI(this, "wxaa055b4833fdbf4a", false);
		}
		if (!mWeixinAPI.isWXAppInstalled()) {
			//提醒用户没有按照微信
			ToolKits.toast(Login.this,"没有安装微信");
			if (mLoadingDialog.isShowing() && !this.isFinishing())
				mLoadingDialog.dismiss();
			return;
		}
		UMWXHandler wxHandler = new UMWXHandler(Login.this,
				"wxaa055b4833fdbf4a", "c4f199bd5983ae9309c8bcb4f3bcd0e4");
		wxHandler.addToSocialSDK();
		myLoginSevice.loginWithWeChat();
	}

	@OnClick(R.id.tvQQ)
	public void onLoginByQQClick(View view) { // TODO //QQ登录
		UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(Login.this,
				"1104588970", "JVSuqFVQjNWJJvSI");
		qqSsoHandler.addToSocialSDK();
		// myLoginSevice.deteteOauth();
		myLoginSevice.loginWithQQ();
		// try {
		// type = SNSType.AVOSCloudSNSQQ;
		// SNS.setupPlatform(this, SNSType.AVOSCloudSNSQQ, "1104588970",
		// "JVSuqFVQjNWJJvSI",
		// "https://leancloud.cn/1.1/sns/callback/pc5j37rylq4nd1o8");
		//
		// SNS.loginWithCallback(Login.this, SNSType.AVOSCloudSNSQQ,
		// new SNSCallback() {
		//
		// @Override
		// public void done(SNSBase base, SNSException error) {
		// if (error == null) {
		// Log.e("==login=","login succeed");
		// Map<String,Object> userInfo = base.userInfo();
		// StringBuilder sb = new StringBuilder();
		// Set<String> keys = userInfo.keySet();
		// for (String key : keys) {
		// sb.append(key + "=" + userInfo.get(key).toString() + "\r\n");
		// }
		// Log.e("TestData", sb.toString());
		// // SNS.loginWithAuthData(base.userInfo(), new LogInCallback<AVUser>()
		// {
		// // @Override
		// // public void done(AVUser user, AVException error) {
		// //
		// // }
		// // });
		// }
		// }
		// });
		// } catch (AVException e) {
		// e.printStackTrace();
		// }

		// try {
		// type = SNSType.AVOSCloudSNSQQ;
		// SNS.setupPlatform(SNSType.AVOSCloudSNSQQ,
		// "https://leancloud.cn/1.1/sns/goto/pc5j37rylq4nd1o8");
		// /*
		// * 这个url是在app下对应的组件中的SNS页面，在保存相应平台后的appId和app SecretId之后生成的登录URL
		// * 同时，你需要将生成的回调URL，填写到相应平台的回调地址中间去
		// */
		//
		// SNS.loginWithCallback(Login.this, SNSType.AVOSCloudSNSQQ,
		// new SNSCallback() {
		//
		// @Override
		// public void done(SNSBase base, SNSException error) {
		// if (error == null) {
		// Log.e("==login=","login succeed");
		//
		// // SNS.loginWithAuthData(base.userInfo(), new LogInCallback<AVUser>()
		// {
		// // @Override
		// // public void done(AVUser user, AVException error) {
		// //
		// // }
		// // });
		// }
		// }
		// });
		// } catch (AVException e) {
		// e.printStackTrace();
		// }

	}

	/**
	 * 重写onKeyDown方法
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showExitAlet();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void showExitAlet() {
		if ((System.currentTimeMillis() - mExitTime) > 2000) {
			Toast toast = Toast.makeText(Login.this, "再按一次退出程序",
					Toast.LENGTH_LONG);
			// 可以控制toast显示的位置
			toast.setGravity(Gravity.BOTTOM, 0, 150);
			toast.show();
			mExitTime = System.currentTimeMillis();

		} else {
			Login.this.finish();
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		for (MyOnTouchListener listener : touchListeners) {
			listener.onTouchEvent(event);
		}
		return super.onTouchEvent(event);
	}

	private ArrayList<MyOnTouchListener> touchListeners = new ArrayList<MyOnTouchListener>();

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}
}
